package com.turman.builibrary.refresh;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class BScrollUtil {
    /**
    * 判断当前view是否发生滚动
    * @author buobao
    * @since 2024/3/14 10:36
    */
    public static boolean childScrolled(@NonNull View child) {
        if (child instanceof AdapterView) {
            AdapterView view = (AdapterView) child;
            //判断第一个可见的item是否可见，或者第一个项是否全部可见
            if (view.getFirstVisiblePosition() != 0
                    || view.getFirstVisiblePosition() == 0 && view.getChildAt(0) != null
                    && view.getChildAt(0).getTop() < 0) {
                return true;
            }
        }
        if (child instanceof RecyclerView) {
            RecyclerView recyclerView = (RecyclerView) child;
            View view = recyclerView.getChildAt(0);
            int firstPosition = recyclerView.getChildAdapterPosition(view);
            return firstPosition != 0 || view.getTop() != 0;
        }
        if (child instanceof ScrollView) {
            ScrollView scrollView = (ScrollView) child;
            if (scrollView.getScrollY() >0) {
                return true;
            }
        }
        return false;
    }

    public static View findScrollableChild(@NonNull ViewGroup parent) {
        if (parent.getChildCount() <= 1) {
            return null;
        }
        View child = parent.getChildAt(1); //这里第一个通常是header，所以从第二个开始查
        if (child instanceof RecyclerView || child instanceof AdapterView) {
            return child;
        }

        if (child instanceof ViewGroup) {
            View tempChild = ((ViewGroup) child).getChildAt(0);
            if (tempChild instanceof RecyclerView || tempChild instanceof AdapterView) {
                child = tempChild;
            }
        }
        return child;
    }
}
